package it.polimi.travelDream.ejb.beans;

import it.polimi.travelDream.ejb.Cthulhu.Persistenza;
import it.polimi.travelDream.ejb.interfaces.StaffMgrRemote;
import it.polimi.travelDream.entities.Staff;
import it.polimi.travelDream.entities.User;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 * Session Bean implementation class StaffMgr
 */
@Stateless
@LocalBean

public class StaffMgr implements StaffMgrRemote {

	Staff staff;
	Persistenza persist=new Persistenza();
    public Staff getStaff() {
		return staff;
	}

	public void setStaff(Staff staff) {
		this.staff = staff;
	}
    /**
     * Default constructor. 
     */
    public StaffMgr() {
        // TODO Auto-generated constructor stub
    }
    
	/**
	 * @author Filipazzi, Crisciullo
	 * This method is used by a System Administrator
	 * It adds an employee to the system
	 */

	@Override
	public Staff addEmployee(boolean permission, String username,
			String password, String mail, String name, String surname) {
		
		Staff newstaff=new Staff(1,permission, username, name, surname, mail, password);
		persist.persista(newstaff);
		return newstaff;
	}

	@Override
	public void delEmployee() {
		// TODO Auto-generated method stub
		
	}

	/**
	 * @author Filipazzi, Crisciullo
	 * This is the login method used by a staff member
	 */
	@Override
	public Staff validate_login(String username, String password) {
            Staff u;
            EntityManagerFactory logfactory=Persistence.createEntityManagerFactory("it.polimi.travelDream");
    		EntityManager logem=logfactory.createEntityManager();
    		
            try {
            	

                    Query q = logem.createQuery("SELECT u FROM Staff u WHERE u.username=:username");
                    q.setParameter("username", username);
                    System.out.println("tanta robba");
                    u = (Staff)q.getSingleResult();
                    System.out.println(u.getPassword()+" "+password+" "+u.getPassword().equals(password));
                 if (u.getPassword().equals(password)){
                	 System.out.println("tanta robba3");
                     logem.close();
                     logfactory.close();
                     return u;
                 }
                 else {
                	 return null;
                 }
                 
            }
            catch (Exception e) {
            	 logem.close();
                 logfactory.close();
            	System.out.println("ECCEZIONE:\nERROR: " + e.getMessage());
                    return null;
            }
            
    }

	@Override
	public void logout() {
		// TODO Auto-generated method stub
		
	}
	

}
